﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace DriverLicence.Cnsl.Entities
{
    public class Quiz
    {
        private int _accerts = 0;
        private int? _selectedCantQuestions;
        private int _currentQuestion = -1;

        private Question CurrentQuestion
        {
            get
            {
                return this.Questions[this._currentQuestion];
            }
        }
        
        public string Title { get; set; }
        public Question[] Questions { get; set; }

        public int GetTotalCantQuestions()
        {
            return this.Questions.Length;
        }

        public void SetCantQuestions(int selectedCantQuestions)
        {
            if (this._selectedCantQuestions.HasValue)
            {
                throw new InvalidOperationException();
            }
            if (selectedCantQuestions > this.GetTotalCantQuestions())
            {
                throw new IndexOutOfRangeException();
            }

            this._selectedCantQuestions = selectedCantQuestions;
            var rnd = new Random();
            this.Questions = this.Questions.OrderBy(x => rnd.Next()).ToArray();
        }

        public bool GetNextQuestion()
        {
            bool increment = _currentQuestion < _selectedCantQuestions.Value - 1;
            if (increment)
            {
                this._currentQuestion++;
            }
            return increment;
        }

        public string GetCurrentQuestionStatement()
        {
            return this.Questions[this._currentQuestion].Statement;
        }

        public IAnswer[] GetCurrentQuestionOptions()
        {
            CurrentQuestion.RandomSort();
            return CurrentQuestion.Options;
        }

        public string ChooseOption(int index)
        {
            var selectedOption = CurrentQuestion.Options[index];
            string result = selectedOption.AnswerMessage;
            if(selectedOption.IsCorrectAnswer)
            {
                this._accerts++;
            }
            else
            {
                result = string.Format("{0}. The correct one was: '{1}'.",
                                result, CurrentQuestion.GetRigthOption().Value);
            }
            return result;
        }

        public float GetResult()
        {
            if(this._currentQuestion < this._selectedCantQuestions - 1)
            {
                throw new InvalidOperationException();
            }
            return this._accerts / (float)this._selectedCantQuestions.Value * 100;
        }
    }
}
